package cn.com.wind.bdg.collect.collect.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Properties;

public class PropertyFileUtil {

	private static final Logger logger = LoggerFactory.getLogger(PropertyFileUtil.class);

	/**
	*@Description 加载配置文件
	*@Param [path] 配置文件的路径
	*@Return java.util.Properties 配置对象
	*@Author wsun.Frank
	*@Date 2020/8/12
	*/
	public static Properties load(String path) {
		InputStream stream = findInUserDir(path);
		if (stream == null) {
			stream = findInResource(path);
		}
		if (stream == null) {
			return null;
		}
		Properties properties = new Properties();
		try {
			properties.load(stream);
		} catch (IOException ex) {
			throw new RuntimeException(ex);
		}
		return properties;
	}

	private static InputStream findInUserDir(String file) {
		String userDir = System.getProperty("user.dir");
		if (userDir != null) {
			File f = new File(userDir, file);
			if (f.exists() && f.isFile()) {
				try {
					FileInputStream in = new FileInputStream(f);
					logger.info("加载配置：" + f.getAbsolutePath());
					return in;
				} catch (FileNotFoundException e) {
					return null;
				}
			}
		}
		return null;
	}

	private static InputStream findInResource(String file) {
		logger.info("加载配置：classpath:/" + file);
		return PropertyFileUtil.class.getResourceAsStream("/" + file);
	}
}
